package com.autonavi.yunda.yunji.controller.interceptor;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.buc.sso.client.vo.BucSSOUser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Interceptor for logging operation name and buc user
 * @author ruirui.cr@alibaba-inc.com
 */
@Slf4j
public class OperationInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER_OP_LOGGER
            = LoggerFactory.getLogger("logger.operation.log");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod= (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            NeedOperationLog needOperationLog = method.getAnnotation(NeedOperationLog.class);
            if(null != needOperationLog){
                //Get BUC User
                BucSSOUser bucSSOUser = SimpleUserUtil.getBucSSOUser(request);
                String operationName = needOperationLog.operationName();
                String employeeId = null == bucSSOUser? "unknown": bucSSOUser.getEmpId();
                LOGGER_OP_LOGGER.info("{}, {}", employeeId, operationName);
            }
        }
        return true;
    }
}
